package com.opennews.openplatform.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.time.Instant;
import java.util.Map;

public class SharedUtil {
    /**
     * Sends http error to client as request response.
     * Example:
     * {
     * success: false,
     * timestamp: 1642586379,
     * status: 401,
     * error: "UNAUTHORIZED",
     * message: "ERROR_USER_ACCOUNT_NOT_AUTHORIZED",
     * path: "/family-expense/api/user"
     * }
     *
     * @param response:   Http response.
     * @param httpStatus: Http status.
     * @param error:      String to identify error.
     * @param message:    String of more specific message.
     * @param path:       String of request url path.
     */
    public static void sendErrorResponse(HttpServletResponse response, int httpStatus, String error, String message, String path) {
        response.resetBuffer();
        response.setStatus(httpStatus);
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

        try {
            response.getOutputStream().print(new ObjectMapper().writeValueAsString(Map.of(
                    "success", false,
                    "timestamp", Instant.now().getEpochSecond(),
                    "status", httpStatus,
                    "error", error,
                    "message", message,
                    "path", path
            )));

            // Marks response as committed -- if we don't do this the request will go through normally!
            response.flushBuffer();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
